#!/usr/bin/perl
# Copyright (C) 2009-2013 Zentyal S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# Script: duplicity-wrapper
#
# Wrapper to not expose duplicity password via sh -c

use warnings;
use strict;

use EBox::Config;
use EBox::EBackup;
use EBox::EBackup::Password;
use EBox::Sudo;
use String::ShellQuote;

my %originalArgv = map { $_ => 1 } @ARGV;

my $debug = EBox::Config::boolean('debug');

my $TIMEOUT = EBox::Config::configkey('duplicity_timeout');
unless ($TIMEOUT) {
    $TIMEOUT = 300; # in seconds, 5 minutes
}

# set environment variables for passwords
my $alternativePasswordArg = '--alternative-password';
my $alternativePassword = $originalArgv{$alternativePasswordArg};
if ($alternativePassword) {
    @ARGV = grep {
        $_ ne $alternativePasswordArg
    } @ARGV;
}

$ENV{HOME} = '/root';

# set remote server password
my $password =   EBox::EBackup::Password::passwd($alternativePassword);
$ENV{FTP_PASSWORD} = $password;
$ENV{RSYNC_PASSWORD} = $password;

# temp directory
unless ($originalArgv{'--tempdir'}) {
    push @ARGV, '--tempdir' => EBox::EBackup::tempdir();
}
# archive directory
unless ($originalArgv{'--archive-dir'}) {
    push @ARGV, '--archive-dir' => EBox::EBackup::archivedir();
}

# gpg keys management
if ($originalArgv{'--encrypt-key'}) {
    my $gpgDir = EBox::Config::home() . '.gnupg';

    my $gpgPassphrase = EBox::EBackup::Password::gpgPassphrase($alternativePassword);
    $ENV{PASSPHRASE} = $gpgPassphrase;
    $ENV{PASSPHRASE} = 'foobar';

    unless ($originalArgv{'--gpg-options'})  {
     push @ARGV, '--gpg-options';
     push @ARGV, qq{'--homedir=$gpgDir '};
     }
} else {
    # no public key encryption, setup symmetric encryption
    my $symmPassword = EBox::EBackup::Password::symmetricPassword($alternativePassword);
    $ENV{PASSPHRASE} = $symmPassword;
}

if ($debug) {
    my $logFile =  EBox::Config::log() . 'duplicity-debug.log';
    push @ARGV, '--log-file', $logFile;
}

# shell quote @ARGV
@ARGV = map {
    shell_quote($_);
} @ARGV;

my $duplicityCommand = "/usr/bin/duplicity --timeout=$TIMEOUT @ARGV";
if ($debug) {
    my $cmdMsg = "Duplicity command: $duplicityCommand";
    my $cmdLogFile =  EBox::Config::log() . 'duplicity-command.log';
    system "echo `date` $cmdMsg >> $cmdLogFile";
}

EBox::setLocaleEnvironment('C.UTF-8');
exec $duplicityCommand or
    exit 2;
